import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Address } from '../entities/address.entity';

@Injectable()
export class AddressService {
  constructor(
    @InjectRepository(Address)
    private addressRepository: Repository<Address>,
  ) {}

  async createAddress(addressData: Partial<Address>): Promise<Address> {
    const address = this.addressRepository.create(addressData);
    return await this.addressRepository.save(address);
  }

  async getAddressByPhone(phone: string): Promise<Address[]> {
    return await this.addressRepository.find({ where: { phone } });
  }

  async updateAddress(
    id: number,
    addressData: Partial<Address>,
  ): Promise<Address> {
    await this.addressRepository.update(id, addressData);
    const address = await this.addressRepository.findOne({ where: { id } });
    if (!address) {
      throw new Error('Address not found');
    }
    return address;
  }

  async GetDefaultAddress(): Promise<Address> {
    const randomPhone = '21wUM$bnQ~45%eZ(';
    const existingAddress = await this.addressRepository.findOne({
      where: { phone: randomPhone },
    });

    if (existingAddress) {
      return existingAddress;
    }

    const address = this.addressRepository.create({
      phone: randomPhone,
      province: '',
      city: '',
      district: '',
      details: '',
    });

    return await this.addressRepository.save(address);
  }
}
